package LoginUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import persistent.*;

import LoginUtil.User.UserType;

import com.db4o.*;
import com.db4o.cs.Db4oClientServer;
import com.db4o.ext.DatabaseClosedException;
import com.db4o.ext.Db4oIOException;
import com.db4o.ext.InvalidPasswordException;
import com.db4o.query.Predicate;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private final int MAX_LOGIN_ATTEMPTS = 3;
	

public void doGet(HttpServletRequest request, HttpServletResponse response) 
			           throws ServletException, java.io.IOException {
	try
	{	    
		final String username = request.getParameter("usernamebox");
		final String password = request.getParameter("passwordbox");
		
		ObjectContainer container = 
	        (ObjectContainer)request.getAttribute(Db4oServletListener.KEY_DB4O_SESSION);
		
		
		// for initializing the database during debugging:
		if(username.equals("admin") && password.equals("admin")) {
			ObjectSet<User> rs = container.query(new Predicate<User>(){
				public boolean match(User user) {
					return user.getUsername().equals("admin")
							&& user.getPassword().equals("admin");
				}});
			
			if(rs.size() <= 0) {
				User user = new User(username,password);
				user.setFirstName("John");
				user.setLastName("Doe");
				user.setUserType(UserType.Admin);
				container.store(user);
				container.commit();
			}
		}
		
		
		
		System.out.println("Your user name is " + username);          
		   System.out.println("Your password is " + password);

		   try {
			   // query the database for users with the given username
			   ObjectSet<User> rs = container.query(new Predicate<User>() {
					   public boolean match(User user){
					        return user.getUsername().equals(username);}});
			   
			   // if an user with that username exists (assume there's only one)
			   if(rs.size() > 0) {
				   User user = rs.next();
				   
				   if(user.isSuspended()) {
					   response.sendRedirect("invalidLoginSuspended.jsp");
				   
				   // if the password is valid, send a redirect based on user type
				   } else if(user.getPassword().equals(password)) {	
					   SendRedirect(request, response, user);
					   
					   // reset login attempts
					   user.setLoginAttempts(0);
					   
					// otherwise, increment the number of attempts then see if the user needs to be suspended
				   } else if(user.incLoginAttempts() >= MAX_LOGIN_ATTEMPTS) {		
					   user.setSuspended(true);
					   response.sendRedirect("invalidLoginSuspended.jsp");
					   
					// if the user is not suspended yet but the password does not match, send to the regular invalid login screen
				   } else {
					   response.sendRedirect("invalidLogin.jsp");
				   }
				   
				   // because we increment the number of login attempts of the user,
				   // we must store and commit the user
				   container.store(user);
				   container.commit();
			   } else {
				   response.sendRedirect("invalidLogin.jsp");
			   }
			   
		   } catch (Db4oIOException e) {
			   System.out.println("IO Exception on querying the database\n");
			   System.out.println(e.getMessage());
		   } catch (DatabaseClosedException e) {
			   System.out.println(e.getMessage());
		   }
		
	} catch (Throwable theException) {
	     System.out.println(theException); 
	}
  }

private void SendRedirect(HttpServletRequest request,HttpServletResponse response, User user)
	throws IOException {
	
		HttpSession session = request.getSession(true);	    
        session.setAttribute("currentSessionUser",user); 
        
        if(user.getUserType() == UserType.Doctor)
        {
      	  response.sendRedirect("doctorMain.jsp"); //logged-in page  for doctors
        }
        else if(user.getUserType() == UserType.Nurse)
        {
      	  response.sendRedirect("nurseMain.jsp"); //logged-in page for nurses
        }
        else if(user.getUserType() == UserType.Patient)
        {
      	  response.sendRedirect("patientMain.jsp"); //logged-in page for nurses
        }
        else if(user.getUserType() == UserType.Admin)
        {
      	  response.sendRedirect("adminMain.jsp"); //logged-in page for nurses
        }
        else
        {
      	  response.sendRedirect("userLogged.jsp"); //logged-in page 
        }
}
}
